package com.bootlever.framework.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.JSONSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ResourceUtils {

    private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);

    public static Map<String, Object> scanResource(String location, Class clazz) throws IOException {

        Map<String, Object> resourceMap = new ConcurrentHashMap<String, Object>();
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = pathMatchingResourcePatternResolver.getResources(location);
        for (Resource resource : resources) {
            URL path = resource.getURL();
            logger.debug("path:{}", StringUtils.getNString(path));
            String resourcePath;
            if (path == null) {
                resourcePath = resource.getFilename();
            } else {
                resourcePath = path.getPath();
            }
            logger.debug("resourcePath:{}", resourcePath);
            logger.info("正在从[{}]读取数据...",resourcePath);
            InputStream is = resource.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int nRead;
            while ((nRead = is.read(buffer)) > 0) {
                baos.write(buffer, 0, nRead);
                baos.flush();
            }
            List<Object> obj = JSONArray.parseArray(new String(baos.toByteArray()),clazz);
            resourceMap.put(resourcePath, obj);
            is.close();
            baos.close();
        }
        return resourceMap;
    }
}
